import redis
import time
import uuid
from flask import Flask, request, jsonify
import gevent
app = Flask(__name__)
rds = redis.Redis.from_url("redis://:difyai123456@47.76.93.134:6379/0")

MAX_CONCURRENT = 3
LOCK_TIMEOUT = 10

LUA_SEMAPHORE = """
-- KEYS[1] = semaphore key
-- ARGV[1] = now
-- ARGV[2] = timeout
-- ARGV[3] = max concurrent
-- ARGV[4] = token

redis.call("ZREMRANGEBYSCORE", KEYS[1], 0, ARGV[1] - ARGV[2])
local current = redis.call("ZCARD", KEYS[1])
if tonumber(current) >= tonumber(ARGV[3]) then
    return 0
end
redis.call("ZADD", KEYS[1], ARGV[1], ARGV[4])
return 1
"""

@app.route("/api/t1")
def t1():
    user_id = request.headers.get("X-USER_ID")
    if not user_id:
        return jsonify({"error": "缺少 X-USER_ID 请求头"}), 400

    sema_key = f"sema:user:{user_id}"
    token = str(uuid.uuid4())
    now = time.time()
    allowed = rds.eval(
        LUA_SEMAPHORE,
        1,
        sema_key,  # semaphore key
        now,                     # now
        LOCK_TIMEOUT,            # timeout
        MAX_CONCURRENT,          # max concurrent
        token                    # token
    )
    if allowed == 0:
        return jsonify({"error": "并发超限"}), 429
    try:
        gevent.sleep(2) # time.sleep(2) 是阻塞的
        return jsonify({"msg": "请求处理完成", "user_id": user_id})
    finally:
        rds.zrem(sema_key, token)
